<template>
    <div class="forgot-pwd-container">
        <!-- 导航栏 -->
        <TmallNavBar>
            <template #default>找回密码</template>
			<template #right>
				<i class="icon iconfont icon-shouye1" @click="$router.push({path: '/'})"></i>
			</template>
        </TmallNavBar>

        <div class="forgot-pwd-inner">
            <!-- 头部切换 -->
            <div class="forgot-pwd-header">
                <div class="forgot-pwd-logo">三叉戟商城</div>
                <div class="header-title-box">
                    <div class="header-title" @click="forgotType = 1" :class="forgotType == 1 ? 'on' : ''">手机找回</div>
                    <div class="header-title" @click="forgotType = 2" :class="forgotType == 2 ? 'on' : ''">邮箱找回</div>
                </div>
            </div>
  
            <!-- 主体 -->
            <div class="forgot-pwd-content">
                <!-- 手机找回 -->
                <div class="forgot-pwd-item" :class="{on: forgotType == 1}">
                    <div class="forgot-pwd-box">

                    <!-- 基础表单校验 -->
                    <van-form @submit="showSetPasswordPopup">
                        <!-- 手机号 -->
                        <van-field
                            v-model="mobileFormData.mobile"
                            :label-width="labelWidth"
                            type="number"
                            name="手机号"
                            label="手机号"
                            placeholder="请输入手机号"
                            left-icon="phone-o"
                            maxlength="11"
                            :rules="[
                                { required: true, message: '请输入手机号' },
                                { validator: mobileValidator, message: '请输入正确格式的手机号' }
                            ]"
                        />
                        
                        <!-- 验证码 -->
                        <van-field
                            v-model="mobileFormData.code"
                            type="number"
                            name="验证码"
                            label="验证码"
                            :label-width="labelWidth"
                            placeholder="请输入验证码"
                            left-icon="lock"
                            maxlength="6"
                            :rules="[{ required: true, message: '请输入验证码' }]"
                        >
                            <template #button>
                                <van-button
                                    class="code-btn"
                                    size="small"
                                    :disabled="!rightMobile"
                                    :color="!rightMobile ? 'gray' : '#27BA9B'"
                                    type="primary"
                                    @click="sendCode"
                                >
                                    {{time ? '剩余' + time + 's' : '发送验证码'}}
                                </van-button>
                            </template>
                        </van-field>

                        <!-- 按钮 -->
                        <div style="margin: 16px">
                            <van-button
                                type="primary"
                                native-type="submit"
                                round
                                block
                                color="#27BA9B"
                            >
                                下一步
                            </van-button>
                        </div>
                    </van-form>
                    </div>
                </div>
    
                <!-- 邮箱找回 -->
                <div class="forgot-pwd-item" :class="{on: forgotType == 2}">
                    <div class="forgot-pwd-box">
                        <!-- 基础表单校验 -->
                        <van-form @submit="showSetPasswordPopup">
                            <!-- 邮箱 -->
                            <van-field
                                v-model="emailFormData.email"
                                :label-width="labelWidth"
                                name="邮箱"
                                label="邮箱"
                                placeholder="请输入邮箱"
                                left-icon="envelop-o"
                                maxlength="30"
                                :rules="[
                                    { required: true, message: '请输入邮箱' },
                                    { validator:emailValidator, message: '请输入正确格式的邮箱' }
                                ]"
                            />
                            
                            <!-- 验证码 -->
                            <van-field
                                v-model="emailFormData.code"
                                type="number"
                                name="验证码"
                                label="验证码"
                                :label-width="labelWidth"
                                placeholder="请输入验证码"
                                left-icon="lock"
                                maxlength="6"
                                :rules="[{ required: true, message: '请输入验证码' }]"
                            >
                                <template #button>
                                    <van-button
                                        class="code-btn"
                                        size="small"
                                        :disabled="!rightEmail"
                                        :color="!rightEmail ? 'gray' : '#27BA9B'"
                                        type="primary"
                                        @click="sendEmailCode"
                                    >
                                        {{exprieTime ? '剩余' + exprieTime + 's' : '发送验证码'}}
                                    </van-button>
                                </template>
                            </van-field>

                            <!-- 按钮 -->
                            <div style="margin: 16px">
                                <van-button
                                    type="primary"
                                    native-type="submit"
                                    round
                                    block
                                    color="#27BA9B"
                                >
                                    下一步
                                </van-button>
                            </div>
                        </van-form>
                    </div>
                </div>

                <!-- 底部导航 -->
                <div class="footer-wapper">
                    <div @click="goto('/passwordLogin')">密码登录</div>
                    <div @click="goto('/register')" style="font-size: 18px;color: #E83915;">还没有账户</div>
                    <div @click="goto('/messageLogin')">短信登录</div>
                </div>
            </div>
        </div>
    </div>
  
    <!-- 弹层 -->
    <van-popup
        v-model:show="showPopup"
        position="bottom"
        background-color="#fff"
    >
      <div class="pwd-panel">
        <!-- 关闭按钮 -->
        <span class="close iconfont icon-guanbi" @click="closePopup"></span>
        
        <!-- 标题 -->
        <div class="title">设置新密码</div>
  
        <van-form @submit="handleSave">
            <!-- 新密码 -->
            <van-field
                v-model="formData.new_password"
                :label-width="60"
                type="password"
                name="密码"
                label="密码"
                left-icon="lock"
                placeholder="请输入密码"
                :rules="[{ required: true, message: '请输入密码' }]"
            />
          
            <!-- 确认密码 -->
            <van-field
                v-model="formData.repassword"
                :label-width="60"
                type="password"
                name="确认密码"
                label="确认密码"
                left-icon="lock"
                placeholder="请输入确认密码"
                :rules="[
                    { required: true, message: '请输入确认密码' },
                    { validator: validatorMessage }
                ]"
            />

            <!-- 按钮 -->
            <div style="margin: 16px">
                <van-button
                    type="primary"
                    native-type="submit"
                    round
                    block
                    color="#27BA9B"
                >
                    保&nbsp;&nbsp;存
                </van-button>
            </div>
        </van-form>
      </div>
    </van-popup>
</template>
  
<script setup>
import { reqEmailForgotPasswordAPI, reqEmailForgotSendCodeAPI, reqMobileForgotPasswordAPI, reqMobileForgotSendCodeAPI } from '@/apis/user'
import { reactive, ref, computed } from 'vue'
import {useRouter} from 'vue-router'
import { showSuccessToast } from 'vant'
  

// 路由器
const router = useRouter() 

// 输入框标签宽度
const labelWidth = ref('50px')


  
// --------------------- 手机找回功能开始 ---------------------
// 手机号验证
const mobileValidator = (value) => /^1[3|5|7|8|9]\d{9}$/.test(value)

const mobileFormData = reactive({
    mobile: '',
    code: ''
})

// 找回方式
const forgotType = ref(1) 
// --------------------- 手机找回功能结束 ---------------------





// --------------------- 邮箱找回功能开始 ---------------------
// 邮箱验证
const emailValidator = (value) => /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value)
const emailFormData = reactive({
    email: '',
    code: ''
})
// --------------------- 邮箱找回功能结束 ---------------------








// ---------------------- 发送验证码功能开始 ----------------------
const rightMobile = computed(() => {
    // 手机正则
    const pattern = /^1[3|5|7|8|9]\d{9}$/
    return pattern.test(mobileFormData.mobile)
})

// 过期时间
const time = ref(0)

// 发送手机验证码
const sendCode = async () => {
    if(time.value == 0) {
        // 请求验证码接口
        await reqMobileForgotSendCodeAPI(mobileFormData.mobile)
        
        showSuccessToast('发送验证码成功')
        
        time.value = 60
        const intervalId = setInterval(() => {
            time.value--
            if(time.value == 0) {
                clearInterval(intervalId)
            }
        }, 1000)
    }
}

//////////////////////////////////////////////////////////////////

const rightEmail = computed(() => {
    // 邮箱正则
    const pattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
    return pattern.test(emailFormData.email)
})

// 过期时间
const exprieTime = ref(0)

// 发送邮箱验证码
const sendEmailCode = async () => {
    if(exprieTime.value == 0) {
        // 请求验证码接口
        await reqEmailForgotSendCodeAPI(emailFormData.email)
        
        showSuccessToast('发送成功')

        exprieTime.value = 60
        const intervalId = setInterval(() => {
            exprieTime.value--
            if(exprieTime.value == 0) {
                clearInterval(intervalId)
            }
        }, 1000)
    }
}
// ---------------------- 发送验证码功能结束 ----------------------





// ---------------------- 点击下一步功能开始 ----------------------
const showPopup = ref(false)
const formData = reactive({
    new_password: '',
    repassword: '',
})

// 打开设置新密码弹层
const showSetPasswordPopup = () => {
    formData.new_password = ''
    formData.repassword = ''
    showPopup.value = true
}


// 关闭弹层
const closePopup = () => {
    showPopup.value = false
}
// ---------------------- 点击下一步功能结束 ----------------------





// ---------------------- 保存新密码功能开始 ----------------------
// 确认密码
const validatorMessage = (value) => {
    return value != formData.new_password ? '两次密码不一致' : '' 
}

const handleSave = async () => {
    // 手机找回
    if (forgotType.value == 1) {
        await reqMobileForgotPasswordAPI({
            mobile: mobileFormData.mobile,
            new_password: formData.new_password,
            repassword: formData.repassword,
            code: mobileFormData.code
        })
    } else { // 邮箱找回
        await reqEmailForgotPasswordAPI({
            email: emailFormData.email,
            new_password: formData.new_password,
            repassword: formData.repassword,
            code: emailFormData.code
        })
    }

    showSuccessToast('找回成功')
    showPopup.value = false

    setTimeout(() => {
        router.push({path: '/passwordLogin'})
    },1000)
}
// ---------------------- 保存新密码功能结束 ----------------------






// ------------------------- 跳转功能开始 ------------------------
const goto = (url) => {
    router.push({path: url})
}
// ------------------------- 跳转功能结束 ------------------------

</script>
  
<style lang="scss">
  .forgot-pwd-container{
    width: 100%;
    height: 100%;
    background: #fff;
    .forgot-pwd-inner {
      padding-top: 90px;
      width: 95%;
      margin: 0 auto;
      .forgot-pwd-header {
        .forgot-pwd-logo {
          font-size: 40px;
          font-weight: bold;
          color: #27BA9B;
          text-align: center;
        }
        .header-title-box {
          display: flex;
          padding-top: 40px;
          align-items: center;
          justify-content: center;
          .header-title {
            color: #333;
            font-size: 18px;
            padding-bottom: 4px;
            
            &:first-child {
              margin-right: 40px;
            }
            &.on {
              color: #27BA9B;
              font-weight: 700;
              border-bottom: 2px solid #27BA9B;
            }
          }
        }
      }
      .forgot-pwd-content {
        .forgot-pwd-item {
          display: none;
          &.on {
            display: block;
          }
  
          .forgot-pwd-box {
            position: relative;
            top: 5px;
            margin: 0 20px;
            .forgot-pwd-btn {
              background-color: #27BA9B;
              color: white;
              width: 100%;
              border-radius: 25px;
            }
            .code-box {
              display: flex;
              justify-content: space-between;
              .code-btn {
                background-color: darkgray;
                width: 90px;
                height: 35px;
                line-height: 35px;
                color: #fff; 
                font-size: 12px;
                margin-left: 50px;
                &.active {
                  background-color: #27BA9B;
                }
              }
            }
          }
        }
      }
    }
  }
  
  .footer-wapper {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      margin-top: 10px;
      color: #909399;
  }
  .pwd-panel {
    padding: 0 15px;
    border-radius: 5px 5px 0 0;
    position: relative;
    background-color: #fff;
  }
  
  .title {
    line-height: 1;
    padding: 20px 0;
    text-align: center;
    font-size: 20px;
    font-weight: normal;
    font-weight: bold;
    border-bottom: 1px solid #ddd;
    color: #444;
  }
  
  .close {
    position: absolute;
    right: 12px;
    top: 12px;
    font-size: 25px;
    color: #27BA9B;
  }
  .save-btn {
    background-color: #27BA9B;
    color: white;
    width: 100%;
    border-radius: 25px;
    margin-bottom: 5px;
  }
</style>